//
//  UserManager.m
//  MiAiApp
//
//  Created by 徐阳 on 2017/5/22.
//  Copyright © 2017年 徐阳. All rights reserved.
//

#import "UserManager.h"
#define kSTRING1(value) [self valueToString:value]//任意类型转换成字符串

@implementation UserManager


+ (instancetype)sharedUserManager{
    static UserManager * instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

/*
 任何对象转字符串 代替以下方法
 
 @param obj 对象
 @return 字符串
 */
-(NSString *)valueToString:(id)obj{
    
    if ([obj isEqual:nil]) {
        return [NSString string];
    }
    
    if ([obj isEqual:[NSNull null]]) {
        return [NSString string];
    }
    
    if ([obj isKindOfClass:[NSString class]]) {
        return obj;
    }
    
    if ([obj isKindOfClass:[NSNumber class]]) {
        return [NSString stringWithFormat:@"%@", obj];
    }
    
    return [NSString string];
}

-(NSString *)getToken{
    //全局的token
    if (kSTRING([UserManager sharedUserManager].userInfo.token).length > 0) {
        return kSTRING([UserManager sharedUserManager].userInfo.token);
    }
    //缓存的token
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"];
    if (kSTRING(token).length > 0) {
        [UserManager sharedUserManager].userInfo.token = token;
        return token;
    }
    return @"";
}

-(void)clearUserInfo{
    [UserManager sharedUserManager].userInfo = nil;
    [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:@"userInfo"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"userToken"];
}

-(void)saveUserInfo:(NSDictionary *)data{
    NSString *userId = data[@"userId"];
    if (!userId) {
        return;
    }
    UserInfo *userInfo = [UserInfo modelWithDictionary:data];
    [UserManager sharedUserManager].userInfo = userInfo;
    [[NSUserDefaults standardUserDefaults] setObject:[ZCTool objectToJson:data] forKey:@"userInfo"];
}

-(UserInfo *)curUserInfo{
    if (kIsTourst) {
        return nil;
    }
    if ([UserManager sharedUserManager].userInfo) {
        return [UserManager sharedUserManager].userInfo;
    }else{
        NSString *dataStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
        NSDictionary *data = [ZCTool dictionaryWithJsonStr:dataStr];
        if ([data isKindOfClass:[NSDictionary class]] && data.allKeys.count > 0) {
            UserInfo *userInfo = [UserInfo modelWithDictionary:data];
            return userInfo;
        }
        return nil;
    }
}

+(void)updateUserDeviceListWith:(NSArray <SLLockModel *>*)deviceList{
    NSString *key = [self localDeviceListKey];
    NSMutableArray *newList = [[NSMutableArray alloc] init];
    [deviceList enumerateObjectsUsingBlock:^(SLLockModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [newList addObject:[obj modelToJSONObject]];
    }];
    
    [[NSUserDefaults standardUserDefaults] setObject:[ZCTool objectToJson:newList] forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//新增开启双模开锁的设备
+(void)insertUserDeviceWith:(SLLockModel *)model{
    NSString *key = [self localDeviceListKey];
    NSString *dataStr = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    NSArray *data = [ZCTool arrayWithJsonStr:dataStr];
    NSMutableArray *newList = [[NSMutableArray alloc] init];
    [newList addObjectsFromArray:data];
    __block NSInteger index = -99;
    [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([model.deviceNo isEqualToString:obj[@"deviceNo"]]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index == -99) {
        [newList addObject:[model modelToJSONObject]];
    }else{
        [newList replaceObjectAtIndex:index withObject:[model modelToJSONObject]];
    }
    [[NSUserDefaults standardUserDefaults] setObject:[ZCTool objectToJson:newList] forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}



//删除双模开锁设备缓存
+(void)deleteUserDeviceWith:(SLLockModel *)deviceModel{
    NSString *key = [self localDeviceListKey];
    NSMutableArray *deviceList = [[NSMutableArray alloc] init];
    NSString *dataStr = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    NSArray *data = [ZCTool arrayWithJsonStr:dataStr];
    [data enumerateObjectsUsingBlock:^(NSDictionary *model, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![deviceModel.deviceNo isEqualToString:model[@"deviceNo"]]) {
            [deviceList addObject:model];
        }
    }];
    [[NSUserDefaults standardUserDefaults] setObject:[ZCTool objectToJson:deviceList] forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


//获取双模开锁的设备数据
+(NSArray *)getUserDeviceList{
    NSString *key = [self localDeviceListKey];
    NSString *dataStr = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    NSArray *data = [ZCTool arrayWithJsonStr:dataStr];
    NSMutableArray *deviceList = [[NSMutableArray alloc] init];
    [data enumerateObjectsUsingBlock:^(NSDictionary *json, NSUInteger idx, BOOL * _Nonnull stop) {
        SLLockModel *model = [SLLockModel modelWithDictionary:json];
        [deviceList addObject:model];
    }];
    return deviceList;
}

+(NSString *)localDeviceListKey{
    NSString *key = [NSString stringWithFormat:@"deviceList_%@",kUserInfo.userId];
    if (kUserInfo.userId.length == 0) key = @"deviceList_visitor";
    return key;
}


//获取产品型号
+(NSArray <SLProductModel *>*)getProductList{
    NSString *key = @"productList";
    NSArray *data = [ZCTool arrayWithJsonStr:[[NSUserDefaults standardUserDefaults] objectForKey:key]];
    NSMutableArray *newProductList = [NSMutableArray new];
    [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [newProductList addObject:[SLProductModel modelWithDictionary:obj]];
    }];
    return newProductList;
}

+(void)updateProductListWith:(NSArray *)productList{
    if (![productList isKindOfClass:[NSArray class]]) {
        return;
    }
    NSString *key = @"productList";
    NSMutableArray *newProductList = [NSMutableArray new];
    [productList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [newProductList addObject:[obj modelToJSONObject]];
    }];
    [[NSUserDefaults standardUserDefaults] setObject:[ZCTool objectToJson:newProductList] forKey:key];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

+(NSDictionary *)removeNilAndNullValuesFromDictionary:(NSDictionary *)dictionary {
    if (!dictionary) {
        return @{}; // 返回空字典
    }
    
    NSMutableDictionary *filteredDictionary = [NSMutableDictionary dictionary];
    
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        // 处理子字典
        if ([value isKindOfClass:[NSDictionary class]]) {
            NSDictionary *filteredSubDict = [self removeNilAndNullValuesFromDictionary:value];
            if (filteredSubDict.count > 0) { // 仅添加非空子字典
                filteredDictionary[key] = filteredSubDict;
            }
        } else if (value != nil && ![value isKindOfClass:[NSNull class]]) {
            filteredDictionary[key] = value; // 只保留非 nil 和非 NSNull 的键值对
        }
    }];
    
    return [filteredDictionary copy]; // 返回不可变字典
}


+(void)updateLogViewWithMessage:(NSString *)message needUnicode:(BOOL)needUnicode{
    if (![ZCTool isOpenDebugModel]) return;
    message = kSTRING(message);
    if ([UserManager sharedUserManager].chatStr == nil) {
        [UserManager sharedUserManager].chatStr = [[NSMutableString alloc] initWithString:@""];
    }
    NSString *newMsg = nil;
    if (needUnicode) {
        newMsg = [self replaceUnicode:message];
    }
    if (newMsg) {
        message = newMsg;
    }
    NSString *timeStr = [NSString dateStrFromDate:[NSDate date] formatStr:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString *logStr = [NSString stringWithFormat:@"\n---------------【%@】<logMessage>---------------\n%@",timeStr,message];
    [[UserManager sharedUserManager].chatStr appendString:logStr];
    
    NSString *date = [NSString dateStrFromDate:[NSDate date] formatStr:@"yyyyMMdd"];
    NSString *key = [NSString stringWithFormat:@"UserLog_%@.txt",date];
    [self writeToTXTFileWithString:logStr fileName:key];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateChatView" object:nil userInfo:nil];
}

+(NSString *)replaceUnicode:(NSString*)unicodeStr{
    
    NSString *tempStr1=[unicodeStr stringByReplacingOccurrencesOfString:@"\\u"withString:@"\\U"];
    NSString *tempStr2=[tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    NSString *tempStr3=[[@"\""stringByAppendingString:tempStr2]stringByAppendingString:@"\""];
    NSData *tempData=[tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                         mutabilityOption:NSPropertyListImmutable
                                                                   format:NULL
                                                         errorDescription:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}

/**
 param
 string:文件内容
 fileName:文件名
 */
+(void)writeToTXTFileWithString:(NSString *)string fileName:(NSString *)fileName {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        @synchronized (self) {
            //获取沙盒路径
            NSArray *paths  = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
            //获取文件路径
            NSString *fullName = [NSString stringWithFormat:@"%@.txt", fileName];
            NSString *theFilePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:fullName];
            //创建文件管理器
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //如果文件不存在 创建文件
            if(![fileManager fileExistsAtPath:theFilePath]){
                [@"" writeToFile:theFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
            }
            NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:theFilePath];
            [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
            NSData* stringData  = [[NSString stringWithFormat:@"%@\n",string] dataUsingEncoding:NSUTF8StringEncoding];
            [fileHandle writeData:stringData]; //追加写入数据
            [fileHandle closeFile];
        }
    });
}


@end
